package com.shuqi.tools.actions;

import com.intellij.openapi.project.Project;
import com.shuqi.tools.dto.BuildConfig;
import com.shuqi.tools.dto.Manifest;
import com.shuqi.tools.utils.Constants;
import com.shuqi.tools.utils.LoggerUtils;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;

/**
 * @author shuqi
 * @description
 * @date 2019-12-10 12:49
 * @since V1.0
 */
public class WechatBuildAction extends AbsBuildAction {
	// ${v5Path}/webapps/seeyon/m3/apps/${team}/${bundleName}
	private String targetPathFormat = "%s" + File.separator + "m3" + File.separator + "apps" + File.separator + "%s" + File.separator +  "%s";

	@Override
	public Constants.BuildType buildType() {
		return Constants.BuildType.WECHAT;
	}

	@Override
	protected void afterPack(Manifest mateMap, BuildConfig config, File outZip, Project project) {
		File target = new File(String.format(targetPathFormat, config.getV5RuntimePath(),mateMap.getTeam(),mateMap.getBundleName()));
		try {
			unZip(outZip,target.getCanonicalPath());
		} catch (IOException e) {
			LoggerUtils.error("", e);
		}

	}
	public static void unZip(File srcFile, String destDirPath) {
		if (!srcFile.exists()) {
			throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
		}
		// 开始解压
		try (ZipFile zipFile = new ZipFile(srcFile) ){
			Enumeration<?> entries = zipFile.getEntries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				// 如果是文件夹，就创建个文件夹
				if (entry.isDirectory()) {
					String dirPath = destDirPath + File.separator + entry.getName();
					File dir = new File(dirPath);
					dir.mkdirs();
				} else {
					// 如果是文件，就先创建一个文件，然后用io流把内容copy过去
					File targetFile = new File(destDirPath + File.separator + entry.getName());
					// 保证这个文件的父文件夹必须要存在
					if(!targetFile.getParentFile().exists()){
						targetFile.getParentFile().mkdirs();
					}
					targetFile.createNewFile();
					// 将压缩文件内容写入到这个文件中
					InputStream is = zipFile.getInputStream((ZipArchiveEntry) entry);
					FileOutputStream fos = new FileOutputStream(targetFile);
					IOUtils.copy(is, fos);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("unzip error from ZipUtils", e);
		}

	}
}
